const fs       = require('fs'),
	http       = require('http'),
	gulp       = require('gulp'),
	del        = require('del'),                              // 删除
	replace    = require('gulp-replace'),                     // 替换
	concat = require('gulp-concat'),
	uglify     = require('gulp-uglify'),                      // 压缩JS
	rename     = require('gulp-rename'),                      // 重命名
	argv       = require('minimist')(process.argv.slice(2));  // 命令行传参

const buildPath = './build/',
	pathConfig = require(buildPath + 'path'),  // 路径目录配置
	consoleLine	= require(buildPath + 'console_line');  // 控制台任务分隔线

//\\----------------------------------------------------------------------------//\\

/**
 * 图标字体任务
 */
var runIconTask = require(pathConfig.icon.build);

gulp.task('icon', function() {
	del([
		pathConfig.icon.dist + '*.*',
		pathConfig.icon.dest + '*.*'
	]).then(function(paths) {
		console.log(consoleLine);
		console.log('[Running] 清理旧字体文件：\n', paths.join('\n '));
		console.log('[Done] 清理完毕！');
		console.log(consoleLine);

		runIconTask(pathConfig.icon, function(name) {
			// 将生成的 icon sass 文件输出到 src 下对应目录
			var tempPath = pathConfig.sass.dest + name + '.scss',
				srcTarget = pathConfig.sass.src[0]
					.replace('**/*.scss', 'bundles');

			gulp.src(tempPath)
				.pipe(gulp.dest(srcTarget))
				.on('end', function() {
					console.log('[Done] 成功生成 iconfont 资源！');

					del(tempPath);
				});
		});
	});
});

//\\----------------------------------------------------------------------------//\\

/**
 * css 任务
 */
var runCSSTask = require(pathConfig.sass.build);

gulp.task('css', function() {
	runCSSTask(pathConfig.sass, pathConfig.packFileName);
});

//\\----------------------------------------------------------------------------//\\

/**
 * js 任务
 * // 2018-01-22 这部分写的比较 low，待有空优化
 */
gulp.task('js', function() {
	fs.readFile(pathConfig.js.template, {
		encoding: 'utf-8'
	}, function(err, data) {
		let jsFiles = gulp.src([pathConfig.js.src, '!' + pathConfig.js.template]),
			dataStrs = data.split('{{ code }}'),
			headReg = /^(;\(|\()function\(\$\)\s*{/,
			footReg = /\}\)\(jQuery\)\;/;

		// 单文件输出
		jsFiles.pipe(replace(headReg, function() {
			return dataStrs[0];
		}))
		.pipe(replace(footReg, function() {
			return dataStrs[1];
		}))
		.pipe(gulp.dest(pathConfig.js.dest))
		.pipe(uglify({mangle: false}))
		.pipe(rename({suffix: '.min'}))
		.pipe(gulp.dest(pathConfig.js.dest))
		.on('end', function() {
			console.log('[Done] JS 文件输出成功');
		});
	});
});
